package com.smartdot.bluetoothidcarddemo.http;

import com.smartdot.bluetoothidcarddemo.App;
import com.smartdot.bluetoothidcarddemo.http.interceptor.AddCookiesInterceptor;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableTransformer;
import io.reactivex.Observer;
import io.reactivex.subjects.PublishSubject;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retofit网络请求工具类
 * Created by LUOLI on 2018/3/16.
 */
public class RetrofitUtils {
    private static final int READ_TIMEOUT = 60;//读取超时时间,单位  秒
    private static final int CONN_TIMEOUT = 12;//连接超时时间,单位  秒
    private static final String TAG = "RetrofitUtils";
    private static Retrofit mRetrofit;
    private static APIService apiService;
    //    private static String baseUrl = BuildConfig.SERVER_ADD;
    private static String baseUrl = "http://120.27.8.220:22080/";

    private RetrofitUtils() {

    }

    public static APIService newInstence() {
        mRetrofit = null;
        apiService = null;
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(CONN_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
//                .addInterceptor(new LoggingInterceptor()) //日志打印
                .addNetworkInterceptor(getHttpLoggingInterceptor())//日志打印
//                .addInterceptor(new TokenInterceptor())//刷新token
                .addInterceptor(new AddCookiesInterceptor(App.getContextObject())) //添加header
                .sslSocketFactory(TrustSSLFactory.getSocketFactory()) //忽略证书
                .hostnameVerifier(TrustSSLFactory.DO_NOT_VERIFY).build();

        mRetrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        apiService = mRetrofit.create(APIService.class);
        return apiService;
    }

    /**
     * 提供Log日志插值器
     */
    public static HttpLoggingInterceptor getHttpLoggingInterceptor() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return loggingInterceptor;
    }

    /**
     * 对observable进行统一转换（包括线程切换，订阅的生命周期管理，失败重试机制）
     *
     * @param observable       被订阅者
     * @param observer         订阅者
     * @param lifecycleSubject 生命周期事件发射者
     */
    public static void composeToSubscribe(Observable observable, Observer observer, PublishSubject<LifeCycleEvent> lifecycleSubject) {
        //默认在进入DESTROY状态时发射一个事件来终止网络请求
        composeToSubscribe(observable, observer, LifeCycleEvent.DESTROY, lifecycleSubject);
    }

    /**
     * @param observable       被订阅者
     * @param observer         订阅者
     * @param event            生命周期中的某一个状态，比如传入DESTROY，则表示在进入destroy状态时lifecycleSubject会发射一个事件从而终止请求
     * @param lifecycleSubject 生命周期事件发射者
     */
    public static void composeToSubscribe(Observable observable, Observer observer, LifeCycleEvent event, PublishSubject<LifeCycleEvent> lifecycleSubject) {
        observable.compose(getTransformer(event, lifecycleSubject)).subscribe(observer);
    }

    /**
     * 获取统一转换的Transformer
     *
     * @param event            生命周期中的某一个状态，比如传入DESTROY，则表示在进入destroy状态时
     *                         lifecycleSubject会发射一个事件从而终止请求
     * @param lifecycleSubject 生命周期事件发射者
     */
    public static <T> ObservableTransformer<T, T> getTransformer(final LifeCycleEvent event, final PublishSubject<LifeCycleEvent> lifecycleSubject) {
        return new DefaultTransformer<>(event, lifecycleSubject);
    }
}
